<script>
import {
  defineComponent,
  reactive,
  toRefs
} from 'vue'

export default defineComponent({
  name: 'ConfigButtonGroup',
  props: {
    size: {
      type: Number,
      default: 16
    },
    category: {
      type: Number,
      default: 0
    },
    border: {
      type: Boolean,
      default: false
    },
    delay: {
      type: Number,
      default: 500
    }
  },
  setup(props, { emit }) {
    const state = reactive({
      handlerTimer: 0,
      isMouseDown: false
    })

    const handleGroupClick = (e) => {
      if(e === 0) {
        emit('left')
      } else {
        emit('right')
      }
    }

    const handleGroupMouseDown = (e) => {
      state.isMouseDown = true
      state.handlerTimer = setInterval(() => {
        if(e === 0) {
          emit('left')
        } else {
          emit('right')
        }
      }, props.delay)
    }

    const handleGroupMouseUp = () => {
      if(state.isMouseDown) {
        clearInterval(state.handlerTimer)
        emit('stop')
        state.isMouseDown = false
      }
    }

    return {
      ...toRefs(state),
      handleGroupClick,
      handleGroupMouseDown,
      handleGroupMouseUp
    }
  }
})
</script>

<template>
  <div class="component-config-button-group-container" :style="{ width: `${ size * 2 + 1 }px`, height: `${size}px`, borderWidth: border ? '2px' : '1px' }">
    <div class="button left" :class="`type-${category}`" @mousedown="handleGroupMouseDown(0)" @mouseup="handleGroupMouseUp(0)" />
    <div class="line" />
    <div class="button right" :class="`type-${category}`" @mousedown="handleGroupMouseDown(1)" @mouseup="handleGroupMouseUp(1)" />
  </div>
</template>

<style lang="scss">
.component-config-button-group-container {
  border: 1px solid #a8a7a7;
  border-radius: 2px;
  overflow: hidden;
  display: flex;
  align-items: center;

  .button {
    width: calc((100% - 1px) / 2);
    height: 100%;
    background-size: 40%;
    background-position: center center;
    background-repeat: no-repeat;
    user-select: none;
    cursor: pointer;

    &.left.type-0 {
      background-image: url('../assets/components/config-buttong-group--left-type0.png');
    }

    &.left.type-1 {
      background-image: url('../assets/components/config-buttong-group--left-type1.png');
    }

    &.right.type-0 {
      background-image: url('../assets/components/config-buttong-group--right-type0.png');
    }

    &.right.type-1 {
      background-image: url('../assets/components/config-buttong-group--right-type1.png');
    }
  }

  .line {
    width: 1px;
    height: 100%;
    border: 1px #a8a7a7 dashed;
  }
}
</style>
